<template>
	<view class="container">

		<view class="user-section">
			<view class="user-info-box">
				<view class="portrait-box">
					<image mode="aspectFill" class="portrait" :src="userInfo.photoUrl || '/static/missing-face.png'" @click="navTo('/pages/set/setUserInfo')"></image>
				</view>
				<view class="b-btn button-base" v-if="!hasLogin" @click="navTo('/pages/public/login')">
					立即登录
				</view>
				<view class="b-btn" v-if="hasLogin">
					<span class="username">{{userInfo.name||'设置昵称'}}</span>
					<uni-tag disabled="true" size="small" :text="userInfo.userLevelName" type="success" @click.native="navTo('/pages/user/level')"/>
				</view>
			</view>
		</view>

		<view class="cover-container" :style="[{
				transform: coverTransform,
				transition: coverTransition
			}]"
		 @touchstart="coverTouchstart" @touchmove="coverTouchmove" @touchend="coverTouchend">

			<view class="tj-sction">
				<view class="tj-item">
					<text class="num" @click="navTo('/pages/user/award')">{{userInfo.availableBalance||0.00}}</text>
					<text class="desc">余额(元)</text>
					<text class="b-btn button-base" @click="navTo('/pages/withdraw/list')">提现</text>
				</view>
				<view class="tj-item" @click="navTo('/pages/user/coupon')">
					<text class="num">{{userInfo.couponCount||0}}</text>
					<text class="desc">优惠券</text>
				</view>
				<view class="tj-item" @click="navTo('/pages/voucher/voucher')">
					<text class="num">{{userInfo.voucherCount||0}}</text>
					<text class="desc">次卡</text>
				</view>
			</view>
			<!-- 订单 -->
			<view class="order-section">
				<view class="order-item" @click="navOrder('/pages/order/order?state=')" hover-class="common-hover" :hover-stay-time="50">
					<uni-icons custom-prefix="custom-icon" type="icon-order-complete" color="#909399" size="40"></uni-icons>
					<text class="desc">全部订单</text>
				</view>
				<view class="order-item" @click="navOrder('/pages/order/order?state=DRAFT')" hover-class="common-hover" :hover-stay-time="50">
					<uni-icons custom-prefix="custom-icon" type="icon-order-pay" color="#909399" size="40"></uni-icons>
					<text class="desc">待付款</text></uni-badge>
				</view>
				<view class="order-item" @click="navOrder('/pages/order/order?state=ASSIGNED')" hover-class="common-hover" :hover-stay-time="50">
					<uni-icons custom-prefix="custom-icon" type="icon-order-confirm" color="#909399" size="40"></uni-icons>
					<text class="desc">待服务</text><uni-badge type="error" v-if="toServiceOrderCount>0" :text="toServiceOrderCount+''"></uni-badge>
				</view>
				<view class="order-item" @click="navTo('/pages/aftersale/list')" hover-class="common-hover" :hover-stay-time="50">
					<uni-icons custom-prefix="custom-icon" type="icon-aftersale" color="#909399" size="40"></uni-icons>
					<text class="desc">退款/售后</text><uni-badge type="error" v-if="afterSaleCount>0" :text="afterSaleCount+''"></uni-badge>
				</view>
			</view>
			<navigator class="image-wrapper" url="/pages/public/preRegisterMerchant">
				<image src="/static/image/recruit.png" mode="aspectFill"></image>
			</navigator>
			<!-- 订单 -->
			<view class="function-section">
				<view class="function-item" @click="navTo('/pages/user/qrcode')" hover-class="common-hover" :hover-stay-time="50">
					<uni-icons custom-prefix="custom-icon" type="icon-qrcode" size="40"></uni-icons>
					<text class="desc">二维码</text>
				</view>
				<view class="function-item" @click="navTo('/pages/product/favorite')" hover-class="common-hover" :hover-stay-time="50">
					<uni-icons type="star-filled" color="#4399fc" size="40"></uni-icons>
					<text class="desc">我的收藏</text>
				</view>
			</view>
			<!-- 浏览历史 -->
			<view class="history-section icon">
				<view class="sec-header" v-if="footPrint.length>0">
					<uni-icons type="eye-filled" size="25" color="#4cd964"></uni-icons>
					<text>浏览历史</text>
				</view>
				<scroll-view scroll-x class="h-list" v-if="footPrint.length>0">
					<image @click="navTo('/pages/product/product?id='+footPrint[footPrint.length-index-1].productUuid)" :src="footPrint[footPrint.length-index-1].productMainImage.url"
					 mode="aspectFill" v-for="(product,index) in footPrint"></image>
				</scroll-view>
				<list-cell icon="location-filled" iconColor="#4399fc" title="地址管理" border="" @eventClick="navTo('/pages/address/address')"></list-cell>
				<list-cell icon="notification" iconColor="#f0ad4e" title="消息中心" border="" @eventClick="navTo('/pages/notice/list')"></list-cell>
				<list-cell icon="gear-filled" iconColor="#606266" title="设置" border="" @eventClick="navTo('/pages/set/set')"></list-cell>
			</view>
		</view>
<!--		<view class="recommend">-->
<!--			为你推荐-->
<!--		</view>-->
<!--		<product-list :productList="goodsList"></product-list>-->
<!--		<uni-load-more :status="loadingType"></uni-load-more>-->
<!--		&lt;!&ndash; 底部分享弹窗 &ndash;&gt;-->
<!--		<uni-popup ref="showshare" :type="type">-->
<!--			&lt;!&ndash; #ifdef H5 &ndash;&gt;-->
<!--			<shareByH5 :shareType='1' :userId="userInfo.userUuid" :shareHref="shareHref" @close="closeShare()"></shareByH5>-->
<!--			&lt;!&ndash; #endif &ndash;&gt;-->

<!--			&lt;!&ndash; #ifdef MP-WEIXIN &ndash;&gt;-->
<!--			<shareByWx :shareType='1' :userId="userInfo.userUuid" :shareImg="userInfo.photoUrl"-->
<!--			 shareTitle="注册会员, 立享佣金!" :shareContent="'我是'+userInfo.name" :shareHref="'/pages/public/register?id='+userInfo.userUuid" @close="closeShare()"></shareByWx>-->
<!--			&lt;!&ndash; #endif &ndash;&gt;-->

<!--			&lt;!&ndash; #ifdef MP-ALIPAY &ndash;&gt;-->
<!--			<shareByAli :shareType='1' :userId="userInfo.userUuid" :shareHref="shareHref" @close="closeShare()"></shareByAli>-->
<!--			&lt;!&ndash; #endif &ndash;&gt;-->

<!--			&lt;!&ndash; #ifdef APP-PLUS &ndash;&gt;-->
<!--			<shareByApp :shareType='1' :userId="userInfo.userUuid" :shareHref="shareHref" @close="closeShare()"></shareByApp>-->
<!--			&lt;!&ndash; #endif &ndash;&gt;-->
<!--		</uni-popup>-->

	</view>
</template>
<script>

	import listCell from '@/components/list-cell';
	import uniBadge from "@/components/uni-badge/uni-badge.vue";
	import uniPopup from "@/components/uni-popup/uni-popup.vue"
	import productList from '@/components/product-list.vue'
	// #ifdef H5
	import shareByH5 from '@/components/share/shareByh5.vue'
	// #endif
	// #ifdef MP-WEIXIN
	import shareByWx from '@/components/share/shareByWx.vue'
	// #endif
	// #ifdef MP-ALIPAY
	import shareByAli from '@/components/share/shareByAli.vue'
	// #endif
	// #ifdef APP-PLUS
	import shareByApp from '@/components/share/shareByApp.vue'

	// #endif
	import {
		mapState,
		mapMutations
	} from 'vuex';
	let startY = 0,
		moveY = 0,
		pageAtTop = true;
	export default {
		components: {
			listCell,
			uniBadge,
			uniPopup,
			productList,
			// #ifdef H5
			shareByH5,
			// #endif
			
			// #ifdef MP-WEIXIN
			shareByWx,
			// #endif
			
			// #ifdef MP-ALIPAY
			shareByAli,
			// #endif
			
			// #ifdef APP-PLUS
			shareByApp,
			// #endif
		},
		data() {
			return {
				type: '',
				coverTransform: 'translateY(0px)',
				coverTransition: '0s',
				moving: false,
				toPayOrderCount:0,
				toServiceOrderCount:0,
				afterSaleCount:0,
				loadingType: '', //加载状态
				pageSize: 5,
				pageNo: 1,
				goodsList: [], //商品列表
			}
		},
		onLoad() {
			this.searchRecommendProduct();
		},
		onReachBottom() {
			if (this.loadingType == 'more') {
				this.pageNo++;
				this.searchRecommendProduct();
			}
		},
		onShareAppMessage(res) {
		    return {
		      title: '我是'+this.userInfo.name+',注册会员,立享佣金!',
			  imageUrl:this.userInfo.photoUrl,
		      path: '/pages/public/register?id=' + this.userInfo.userUuid
		    }
		 },
		// #ifndef MP
		onNavigationBarButtonTap(e) {
			const index = e.index;
			if (index === 0) {
				this.navTo('/pages/set/set');
			} else if (index === 1) {
				// #ifdef APP-PLUS
				const pages = getCurrentPages();
				const page = pages[pages.length - 1];
				const currentWebview = page.$getAppWebview();
				currentWebview.hideTitleNViewButtonRedDot({
					index
				});
				// #endif
				uni.navigateTo({
					url: '/pages/notice/list'
				})
			}
		},
		// #endif
		computed: {
			...mapState(['hasLogin', 'userInfo', 'footPrint', 'applicationConfig']),
			shareHref() {
				let pages = getCurrentPages()
				let page = pages[pages.length - 1]
				// #ifdef H5 || MP-WEIXIN || APP-PLUS || APP-PLUS-NVUE
				return this.$api.request.apiBaseUrl.replace("/groupbuy/rest/","") + '/pages/public/register?id=' + this.userInfo.userUuid;
				// #endif
			
				// #ifdef MP-ALIPAY
				return this.$api.request.apiBaseUrl.replace("/groupbuy/rest/","") + '/pages/public/register?id=' + this.userInfo.userUuid;
				// #endif
			}
		},
		methods: {
			...mapMutations(['login']),
			//查询推荐商品
			searchRecommendProduct() {
				var keyArray = [];
				keyArray.push('ON_SALE');
				keyArray.push('RECOMMEND');
				let searchData = {
					'keyArray': keyArray,
					'onSale': true,
					'recommend': true,
					'startIndex': (this.pageNo - 1) * this.pageSize,
					'pageSize': this.pageSize,
				};
				this.searchProduct(searchData);
			},
			//查询商品
			searchProduct(searchData) {
				//加载中
				this.loadingType = 'loading';
				this.$api.request.goodsList(searchData, res => {
					uni.stopPullDownRefresh();
					if (res.body.status.statusCode === '0') {
						var goodsList = res.body.data.products;
						/* 将商品在购物车的数量设置在cartNum属性中 */
						if(this.hasLogin && this.cartInfo)
							this.$api.util.prodCartNum(goodsList,this.cartInfo);
						if (this.pageNo === 1)
							this.goodsList = goodsList;
						else
							this.goodsList = this.goodsList.concat(goodsList);
						this.total = res.body.data.total;
						if (this.goodsList.length >= this.total) {
							this.loadingType = 'noMore';
						} else {
							this.loadingType = 'more';
						}
					} else {
						this.loadingType = 'more';
						console.log(res.body.status.errorDesc);
					}
				}, true);
			},
			togglePopup(type, open) {
				switch (type) {
					case 'top':
						this.content = '顶部弹出 popup'
						break
			
					case 'bottom':
						this.content = '底部弹出 popup'
						break
					case 'center':
						this.content = '居中弹出 popup'
						break
				}
				this.type = type
				this.$nextTick(() => {
					this.$refs['show' + open].open()
				})
			},
			closeShare() {
				this.$refs.showshare.close();
			},
			inquiryOrderTotal(orderStatus) {
				let searchOptions = {
					keyArray: ['USER','IS_AFTER_SALE','ORDERSTATUS','ORDER_TYPE_LIST'],
					orderTypeList:['0','1','2'],
					userUuid: this.userInfo.userUuid,
					afterSale: false,
					orderStatus: orderStatus
				};
				this.$api.request.searchOrderTotal(searchOptions, res => {
					if (res.body.status.statusCode === '0') {
						var total = res.body.data.total;
						if(orderStatus == 'DRAFT'){
							this.toPayOrderCount = total;
						}else if(orderStatus == 'ASSIGNED'){
							this.toServiceOrderCount = total;
						}
					} else {
						// console.log(res.body.status.errorDesc);
					}
				},true);
			},
			inquiryAfterSaleTotal(statusList) {
				var keyArray = ['USER'];
				let searchOptions = {
					userUuid: this.userInfo.userUuid
				};
				if(statusList &&statusList.length>0){
					keyArray.push('STATUS_LIST');
					searchOptions.statusList = statusList;
				}
				searchOptions.keyArray = keyArray;
				this.$api.request.searchAfterSaleTotal(searchOptions, res => {
					if (res.body.status.statusCode === '0') {
						var afterSaleCount = res.body.data.total;
						this.afterSaleCount = afterSaleCount;
					} else {
						// console.log(res.body.status.errorDesc);
					}
				},true);
			},
			/**
			 * 统一跳转接口,拦截未登录路由
			 * navigator标签现在默认没有转场动画，所以用view
			 */
			navTo(url) {
				if (!this.hasLogin) {
					url = '/pages/public/login';
				}
				uni.navigateTo({
					url:url
				})
			},
			//小程序要求未登录状态必须显示订单页面, 不能直接跳转到登录
			navOrder(url) {
				uni.navigateTo({
					url:url
				})
			},

			customerService() {
				uni.navigateTo({
					url:'/pages/help/help'
				})
			},
			
			registerMerchant() {
				uni.navigateTo({
					url: '/pages/public/preRegisterMerchant'
				})
			},
						
			/**
			 *  会员卡下拉和回弹
			 *  1.关闭bounce避免ios端下拉冲突
			 *  2.由于touchmove事件的缺陷（以前做小程序就遇到，比如20跳到40，h5反而好很多），下拉的时候会有掉帧的感觉
			 *    transition设置0.1秒延迟，让css来过渡这段空窗期
			 *  3.回弹效果可修改曲线值来调整效果，推荐一个好用的bezier生成工具 http://cubic-bezier.com/
			 */
			coverTouchstart(e) {
				if (pageAtTop === false) {
					return;
				}
				this.coverTransition = 'transform .1s linear';
				startY = e.touches[0].clientY;
			},
			coverTouchmove(e) {
				moveY = e.touches[0].clientY;
				let moveDistance = moveY - startY;
				if (moveDistance < 0) {
					this.moving = false;
					return;
				}
				this.moving = true;
				if (moveDistance >= 80 && moveDistance < 100) {
					moveDistance = 80;
				}

				if (moveDistance > 0 && moveDistance <= 80) {
					this.coverTransform = `translateY(${moveDistance}px)`;
				}
			},
			coverTouchend() {
				if (this.moving === false) {
					return;
				}
				this.moving = false;
				this.coverTransition = 'transform 0.3s cubic-bezier(.21,1.93,.53,.64)';
				this.coverTransform = 'translateY(0px)';
			}
		},
		onShow() {
			//同步用户信息
			if (this.hasLogin) {
				this.$api.request.userInfo({
					userUuid: this.userInfo.userUuid
				}, res => {
					if (res.body.status.statusCode === '0') {
						this.login(res.body.data);
					}
				},true);
				//获取待付款和待收货订单数量(0-待付款, 1-待发货， 2-待收货)
				this.inquiryOrderTotal('DRAFT');	
				this.inquiryOrderTotal('ASSIGNED');
				this.inquiryAfterSaleTotal(['0']);
			}
		}
	}
</script>
<style lang='scss'>
	page {
		background: $page-bg-color;
	}
	%flex-center {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	%section {
		display: flex;
		justify-content: space-around;
		align-content: center;
		background: #fff;
		border-radius: 10upx;
	}
	
	.sign-point {
		  position: absolute;
		  right: 100rpx;
		  text-align: center;
		  color: #fff;
		}
		
		.sign-point-text {
		  font-size: 22rpx;
		  margin-top: 4rpx;
		}
		
		.sign-point .iconfont {
			  color: #606266;
			  font-size: 31px;
			  width: 37px;
			  height: 37px;
			  text-align: center;
			  line-height: 37px;
			  border-radius: 50%;
			  display: inline-block;
		}
		
		.customer-service {
		  position: absolute;
		  right: 0rpx;
		  text-align: center;
		  color: #fff;
		}
		
		.customer-service-text {
		  font-size: 22rpx;
		  margin-top: 4rpx;
		}
		
		.customer-service .iconfont {
		  color: $font-color-base;
		  font-size: 60upx;
		  width: 72rpx;
		  height: 72rpx;
		  text-align: center;
		  line-height: 72rpx;
		  border-radius: 50%;
		  display: inline-block;
		}

	.user-section {
		height: 400upx;
		padding: 140upx 30upx 0;
		position: relative;
		background: linear-gradient(to bottom, $base-color 50%, $page-color-base);
	}

	.user-info-box {
		height: 180upx;
		display: flex;
		align-items: center;
		position: relative;
		z-index: 1;

		.portrait {
			width: 130upx;
			height: 130upx;
			border: 5upx solid #fff;
			border-radius: 50%;
		}

		.username {
			font-size: $font-lg;
			color: $font-color-dark;
			margin-left: 20upx;
		}
	}


	.cover-container {
		position: relative;
		padding-bottom: 20upx;
		margin: -30px 10px 10px 10px;
	}

	.tj-sction {
		@extend %section;
		align-items: baseline;
		padding: 20upx 0;
		border-radius: 20upx;
		.tj-item {
			@extend %flex-center;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-base;
			.b-btn {
				margin: 10upx 0 0 0;
				width: 132upx;
				opacity:0.8;
			}
		}

		.num {
			font-size: $font-lg;
			font-weight: bold;
			color: $font-color-dark;
			margin-bottom: 8upx;
		}
		.desc{
			font-size: $font-base;
			color: $font-color-base;
		}
	}

	.order-section {
		@extend %section;
		padding: 28upx 0;
		margin: 20upx 0;
		border-radius: 20upx;
		.order-item {
			position: relative;
			@extend %flex-center;
			border-radius: 10upx;
			font-size: $font-sm;
			color: $font-color-dark;
			.desc{
				font-size: $font-base;
				color: $font-color-base;
				margin-top: 18upx;
			}
		}
		.uni-badge{
			position: absolute;
			top: -2px;
			left: 30px;
			background: $price-color;
			color: #fff;
		}
	}
	.function-section {
		@extend %section;
		padding: 28upx 0;
		margin: 20upx 0;
		border-radius: 20upx;
		.function-item {
			position: relative;
			@extend %flex-center;
			width: 120upx;
			height: 120upx;
			border-radius: 10upx;
			font-size: $font-sm;
			color: $font-color-dark;
			.desc{
				font-size: $font-base;
				color: $font-color-base;
				margin-top: 18upx;
			}
		}
		.uni-badge{
			position: absolute;
			top: -2px;
			left: 30px;
			background: #dd524d;
			color: #fff;
		}
	}

	.history-section {
		padding: 30upx 0 0;
		margin-top: 20upx;
		background: #fff;
		border-radius: 20upx;

		.sec-header {
			display: flex;
			align-items: center;
			font-size: $font-base;
			color: $font-color-dark;
			line-height: 40upx;
			margin-left: 30upx;
		}

		.h-list {
			white-space: nowrap;
			padding: 30upx 30upx 0;

			image {
				display: inline-block;
				width: 160upx;
				height: 160upx;
				margin-right: 20upx;
				border-radius: 10upx;
			}
		}
	}
	.recommend{
		text-align: center;
		font-size: $font-lg+8upx;
		color: $font-color-dark;
		font-weight: bold;
		margin-bottom: 20upx;
	}
	.image-wrapper {
		height: 270upx;
		border-radius: 30upx;
		overflow: hidden;
		
		image {
			width: 100%;
			height: 100%;
			opacity: 1;
		}
	}
</style>
